//! TitanV81.js
//! version : 1.0
//! authors : 周成功
//! import $$8 from '../TitanV81';
//! last date : 2021-07-15
//!    TitanV8  2021-06-29 基于方法实例实现，完成基本工具方法
//!    TitanV81 2021-07-15 基于静态对象实现

const TitanV81 = {
    log : function() {
        if(!this.isDefined(arguments) || arguments.length===0) {
            return;
        }
        let args=new Array(arguments.length);
        for (let i = 0; i < arguments.length; i++) {
            args[i] = arguments[i];
        }
        console.log(args);
    }
    ,trim : function(v) {
        let r=this.toString(v);
        return r.replace(/(^\s*)|(\s*$)/g, "");
    }
    ,setValue : function(fieldid, value, reactObj) {
        if(reactObj) {
            reactObj[fieldid] = value;
        }
        let obj = document.getElementById(fieldid);
        if(obj) {
            let ops = obj.options;
            if(ops) {
                /*if(fieldid==="dept_id") {
                    this.log(33, "fieldid", fieldid, "ops.length", ops.length, "value", value);
                }*/
                for(let j=0;j<ops.length; j++){
                    /*if(fieldid==="dept_id") {
                        this.log(44, "j", j, "text", ops[j].text, "value", ops[j].value, "equals", (this.toString(ops[j].value) === this.toString(value)));
                    }*/
                    if(this.toString(ops[j].value) === this.toString(value)) {
                        ops[j].selected = true;
                        break;
                    }
                }
            } else {
                obj.value=value;
            }
        }
    }
    ,toString : function(v) {
        if(!this.isDefined(v)) {
            return "";
        }
        switch (typeof(v)) {
            case 'string':
                return v;
            case 'number':
                return v.toString();
            case 'boolean':
                return v.toString();
            case 'object':
                if (v instanceof Array) {
                    let r = [];
                    for (let i = 0; i < v.length; i++) {
                        r.push(this.toString(v[i]));
                    }
                    return '[' + r.join(',') + ']';
                } else if (v instanceof Date) {
                    let d = "\"" + v.getFullYear();
                    d = d + "-" + (v.getMonth() + 1);
                    d = d + "-" + v.getDate();
                    d = d + " " + v.getHours();
                    d = d + ":" + v.getMinutes();
                    d = d + ":" + v.getSeconds();
                    d = d + "\"";
                    return d;
                } else {
                    let r = [];
                    for ( let p in v) {
                        try {
                            r.push(p + ':' + this.toString(v[p]));
                        } catch (e) {
                            r.push(p + ':unknow');
                        }
                    }
                    return '{' + r.join(',') + '}';
                }
            default:
                throw new Error(`未识别的对象：${v}!`);
        };
    }
    ,isDefined : function(v) {
        if ((v === undefined) || (v === null)) {
            return false;
        }
        let type = typeof (v);
        if ((type === "undefined") || (type === "unknown") || (type === "null")) {
            return false;
        }
        return true;
    }
    ,isEmpty : function(v){
        if(!this.isDefined(v)) {
            return true;
        }
        let type = typeof (v);
        if (type === "string") {
            if (v === "") {
                return true;
            }
            if ((v.replace(/(^\s*)|(\s*$)/g, "")) === "") {
                return true;
            }
        }
        return false;
    }
    ,notEmpty : function(v,name){
        if(this.isEmpty(v)) {
            throw new Error(`请填写${name}!`);
        }
    }
    ,id : function(_id) {
        return document.getElementById(_id);
    }
    /*
    $$8.action("S1701M0201A02", {
    }, function(res){
        if(!$$8.isDefined(res.rows)) {
            return;
        }
        let html = "";
        for(let i=0; i<res.rows.length; i++) {
            let row = res.rows[i];
            html = html + "<button type='button' class='dropdown-item p-1' onclick=\"document.getElementById('route').value=this.innerText;this.parentNode.classList.remove('show');\">"+row+"</button>";
        }
        document.getElementById("divRouteGroupList").innerHTML=html;
    }, function(message){
        window.alert(message);
        document.getElementById("divRouteGroupList").innerHTML="";
    });
    */
    ,action : function(taskid, request, okCallback, errorCallback) {
        let data = request || {};
        data.task = taskid;
        let funcError = errorCallback || function(text) {
            //console.log(["funcError", text]);
            if(text==="[502]Bad Gateway") {
                window.alert("服务Nginx或者S1701未启动。");
            } else {
                window.alert(text);
            }
        };
        let funcOK = okCallback || function(response) {};
        fetch(`${window.SEVER_PATH}/titan/api`, {
            method: 'post',
            headers: {'content-type':'application/json'},
            body: JSON.stringify(data)
        }).then(response => {
            //console.log([taskid, "response", response]);
            if(response.status===200) {
                return response.json();
            } else {
                let msg="["+response.status+"]" + (response.statusText || response.message);
                funcError(msg);
            }
        }).then(res => {
            //this.log(taskid, "res", res);
            if(!this.isDefined(res)) {
                return;
            }
            if(res.status===200) {
                funcOK(res);
            } else {
                let msg="["+res.status+"]" + (res.message || res.statusText);
                funcError(msg);
            }
        }).catch(err => {
            funcError(err.message);
        });
    }
    ,actionSync : function(taskid, request, errorCallback) {
        /*
        const ajaxSync = async ctx => {
            try {
                const data = ctx.request || {};
                data.task = ctx.taskid;
                let json = await (data) => {
                    return new Promise((resolve, reject) => {
                        fetch(`${window.SEVER_PATH}/titan/api`, {
                            method: 'post',
                            headers: {'content-type':'application/json'},
                            body: JSON.stringify(data)
                        }).then(response => {
                            this.log("sync.ajax", "response", response);
                            if(response.status===200) {
                                return response.json();
                            } else {
                                let msg="["+response.status+"]" + (response.statusText || response.message);
                                reject(msg);
                            }
                        }).then(res => {
                            this.log(taskid, "res", res);
                            if(res.status===200) {
                                resolve(res)
                            } else {
                                let msg="["+res.status+"]" + (res.message || res.statusText);
                                reject(msg);
                            }
                        }).catch(err => {
                            reject(err);
                        });
                    });
                };
                return json;
            } catch (err) {
                if(ctx.errorCallback) {
                    ctx.errorCallback(err);
                } else {
                    //console.log(["funcError", text]);
                    if(err==="[502]Bad Gateway") {
                        window.alert("服务Nginx或者S1701未启动。");
                    } else {
                        window.alert(err);
                    }                
                }
            }
        };
        return ajaxSync({'taskid':taskid, 'request':request,  'errorCallback':errorCallback});
        */
        const ajax = async ctx => {
            try {
                let res = await fetch('${window.SEVER_PATH}/titan/api', {task:taskid});
                let data = await res.json();
                console.log(data);
            } catch (err) {
                console.log("错误", err);
            }
        }
        return ajax();
    }
    ,sysdate : function() {
        let res = $$8.actionSync("S1701M0901A04", {
        }, function(message){
            return $$8.toString(new Date());
        });
        if(!$$8.isDefined(res.row)) {
            return $$8.toString(new Date());
        }
        $$8.log("S1701M0901A04", res.row);
        return res.row;
    }

};
window["$$8"] = TitanV81;
export default TitanV81;